package com.guet.service.impl;


import com.guet.domain.SeckillVoucher;
import com.guet.domain.Voucher;
import com.guet.mapper.VoucherMapper;
import com.guet.service.SeckillVoucherService;
import com.guet.service.VoucherService;
import com.guet.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

import static com.guet.utils.RedisConstants.SECKILL_STOCK_KEY;

@Service
public class VoucherServiceImpl implements VoucherService {

    @Resource
    private SeckillVoucherService seckillVoucherService;
    @Autowired
    private VoucherMapper voucherMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;



    @Override
    public void save(Voucher voucher){
        if(voucher.getStatus() == null){
            voucher.setStatus(1);
        }
        voucherMapper.save(voucher);
    }

    @Override
    public Result queryVoucherOfShop(Long shopId) {
        List<Voucher> vouchers = voucherMapper.queryVoucherOfShop(shopId);
        return Result.ok(vouchers);
    }

    @Override
    @Transactional
    public void addSeckillVoucher(Voucher voucher) {
        // 保存优惠券
        save(voucher);
        // 保存秒杀信息
        SeckillVoucher skv = new SeckillVoucher();
        skv.setVoucherId(voucher.getId());
        skv.setStock(voucher.getStock());
        skv.setBeginTime(voucher.getBeginTime());
        skv.setEndTime(voucher.getEndTime());
        seckillVoucherService.save(skv);
        // 保存库存信息到Redis中
        stringRedisTemplate.opsForValue().set(SECKILL_STOCK_KEY + voucher.getId(),voucher.getStock().toString());
    }
}
